#include <stdio.h>  
#include <stdlib.h>  
#include <fcntl.h>  
#include <sys/mman.h>  
#include <unistd.h>  
#include <string.h>  

#include <pthread.h>


#include "ioctl_drv_usr.h"

extern void *fpga_irq_msi_pthd_recv(void *arg);
extern void init_fpga_pcie_dma();
extern void release_fpga_pcie_dma();
extern void init_fpga_pcie_bar();
extern void release_fpga_pcie_bar();
extern int fpga_pcie_dma_recv(int channel, int addr_offset, int data_size, unsigned char *buffer);
extern int fpga_pcie_dma_send(int channel, int addr_offset, int data_size, unsigned char *buffer);
extern int fpga_pcie_bar_write(unsigned char *buffer, unsigned int data_size);
extern int fpga_pcie_bar_read(unsigned char *buffer, unsigned int data_size);

int main(int argc, char **argv)
{
	init_fpga_pcie_dma();
	init_fpga_pcie_bar();
	
#if 1
	int ret = 0;
	pthread_t recv_fpga_pthd;
	ret = pthread_create(&recv_fpga_pthd, NULL, &fpga_irq_msi_pthd_recv, NULL);
	if (0 != ret) {
		printf("recv_fpga_pthd fail=%d! \n\n", ret);
		return ret;
	} else {
		printf("recv_fpga_pthd create ok=%d! \n\n", ret);
	}
	//pthread_join(recv_fpga_pthd, NULL);
	pthread_detach(recv_fpga_pthd);
#endif
	
	//SIZE_4M dma_buffer
	unsigned char dma_buffer[4194304] = {0};
	//4096B bar_buffer
	unsigned char bar_buffer[4096] = {0};
	while(1){
		//fpga app recv working code
		//int fpga_pcie_recv_work(int channel, int addr_offset, int data_size)
		//channel:1,2,3,4,5,6,7		
		//addr_offset:0,1,2,3	每一个偏移量就是当前通道的SIZE大小	
		/*data_size:
			channel 1-->SIZE_4M
			channel 2,3,4-->SIZE_1M
			channel 5,6-->SIZE_8M
			channel 7-->SIZE_16M
		*/
		ret = fpga_pcie_dma_recv(1, 0, SIZE_4M, dma_buffer);
		if (0 != ret) {
			continue;
		} else {
			//do other work
			printf("dma_buffer extract success\n");
			
			//fpga app send working code
			//int fpga_pcie_send_work(int channel, int addr_offset, int data_size, unsigned char *dma_buffer)
			//channel:1,2,3,4
			//addr_offset:0,1,2,3	固定是SIZE_4M,每一个偏移量是SIZE_4M的大小,0是起始的第一个4M地址
			/*data_size:
				channel 1-->2*SIZE_4M
				channel 2-->2*SIZE_4M
				channel 3-->4*SIZE_4M
				channel 4-->1*SIZE_4M	(其中将4M分成2*SIZE_2M使用)
			*/
			ret = fpga_pcie_dma_send(1, 0, SIZE_4M, dma_buffer);
			if (ret != 0) {
				printf("pcie dma send is error\n");
			}
			
			ret = fpga_pcie_bar_write(bar_buffer, 4096);
			if (ret != 0) {
				printf("pcie bar write is error\n");
			}
			
			ret = fpga_pcie_bar_read(bar_buffer, 4096);
			if (ret != 0) {
				printf("pcie bar read is error\n");
			}
			
		}
	}
	
	release_fpga_pcie_bar();
	release_fpga_pcie_dma();
}

/*

pthread compile cmd:
====================
gcc pcie_bar_test.c pcie_dma_test.c test_ctrl.c -o test_ctrl -lpthread

*/